package com.freedom.common.db.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

import java.lang.reflect.Type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

@MappedTypes({List.class})
@MappedJdbcTypes(JdbcType.OTHER)
@SuppressWarnings("UnstableApiUsage")
public class JSONArrayHandler<T> extends BaseTypeHandler<Object> {

    protected TypeToken<T> token;

    public JSONArrayHandler() {
        token = new TypeToken(getClass()) {
        };
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
            throws SQLException {
        PGobject jsonB = new PGobject();
        jsonB.setType("jsonb");
        jsonB.setValue(Objects.isNull(parameter) ? null : JSON.toJSONString(parameter));
        ps.setObject(i, jsonB);
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return readJson(json);
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return readJson(json);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return readJson(json);
    }

    private Object readJson(String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        if (token.isSubtypeOf(List.class)) {
            Type type = token.resolveType(List.class.getTypeParameters()[0]).getType();
            return JSON.parseArray(json, (Class<?>) type);
        }
        return JSON.parseObject(json, token.getRawType());
    }
}
